/**
 * 
 */
package org.intelligentsia.artifacts.repository.metadata.adapter;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import org.intelligentsia.artifacts.repository.metadata.Metadata;
import org.intelligentsia.artifacts.repository.metadata.Plugin;

/**
 * Metadata class Adapter.
 * 
 * @author <a href="mailto:jguibert@intelligents-ia.com" >Jerome Guibert</a>
 * 
 */
public class MetadataAdapter {

	public static Metadata read(JSONObject jsonObject) throws JSONException {
		Metadata metadata = new Metadata();
		metadata.setGroupId(jsonObject.getString("groupId"));
		metadata.setArtifactId(jsonObject.getString("artifactId"));
		metadata.setVersion(jsonObject.getString("version"));
		metadata.setVersioning(VersioningAdapter.read(jsonObject.optJSONObject("versioning")));
		metadata.setPlugins(readPlugins(jsonObject.optJSONObject("plugins")));
		return metadata;
	}

	public static JSONObject write(Metadata metadata) throws JSONException {
		JSONObject jsonObject = null;
		if (metadata != null) {
			jsonObject = new JSONObject();
			jsonObject.putOpt("groupId", metadata.getGroupId());
			jsonObject.putOpt("artifactId", metadata.getArtifactId());
			jsonObject.putOpt("version", metadata.getVersion());
			jsonObject.putOpt("versioning", VersioningAdapter.write(metadata.getVersioning()));
			jsonObject.putOpt("plugins", writePlugins(metadata.getPlugins()));
		}
		return jsonObject;
	}

	public static Metadata readRoot(JSONObject jsonObject) throws JSONException {
		Metadata metadata = null;
		if (jsonObject != null) {
			JSONObject result = jsonObject.optJSONObject("metadata");
			if (result != null)
				metadata = read(result);
		}
		return metadata;
	}

	public static JSONObject writeRoot(Metadata metadata) throws JSONException {
		JSONObject result = null;
		if (metadata != null) {
			result = new JSONObject();
			result.put("metadata", write(metadata));
		}
		return result;
	}

	private static List<Plugin> readPlugins(JSONObject jsonObject) throws JSONException {
		List<Plugin> plugins = null;
		if (jsonObject != null) {
			JSONArray jsonArray = jsonObject.optJSONArray("plugins");
			if (jsonArray != null) {
				plugins = new ArrayList<Plugin>(jsonArray.length());
				for (int i = 0; i < jsonArray.length(); i++) {
					plugins.add(PluginAdapter.read(jsonArray.optJSONObject(i)));
				}
			}
		}
		return plugins;
	}

	private static JSONObject writePlugins(List<Plugin> plugins) throws JSONException {
		JSONObject result = null;
		if (plugins != null && !plugins.isEmpty()) {
			result = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			result.put("plugins", jsonArray);
			for (Plugin plugin : plugins) {
				jsonArray.put(PluginAdapter.write(plugin));
			}
		}
		return result;
	}
}
